package servlet;

import constant.ExamConstant;
import dao.DeptDao;
import model.Dept;
import service.DeptService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/update")
public class DeptUpdate extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Object type = req.getSession().getAttribute(ExamConstant.SESSION_LOGIN_TYPE);
        if (ExamConstant.LOGIN_TYPE_DOCTOR.equals(type)){
            // 设置请求编码格式
            req.setCharacterEncoding("utf-8");
            // 设置响应编码格式
            resp.setContentType("text/html;charset=utf-8");
            // 获取请求信息
            String deptId = req.getParameter("deptId");
            String deptName = req.getParameter("deptName");
            String deptType = req.getParameter("deptType");
            String deptRemark = req.getParameter("deptRemark");
            // 处理请求信息
            Dept dept = new Dept();
            dept.setName(deptName);
            dept.setType(Integer.valueOf(deptType));
            dept.setRemark(deptRemark);
            System.out.println(dept);
            // 调用业务层对象
            DeptService deptService = new DeptService();
            List<Dept> deptList1 = DeptDao.select(Integer.valueOf(deptId),null,null);
            List<Dept> deptList2 = DeptDao.select(null,deptName,null);
            if(deptList1.size()==0 || deptList2.size()>0){
                req.setAttribute("error","输入部门编号不存在或部门名已存在");
                req.getRequestDispatcher(ExamConstant.HOME_PAGE_QUERY).forward(req,resp);
            }else {
                dept.setId(Integer.valueOf(deptId));
                deptService.update(dept);
                resp.sendRedirect(ExamConstant.HOME_PAGE_QUERY);
            }
        }else {
            req.setAttribute("error","请先进行登陆");
            req.getRequestDispatcher(ExamConstant.HOME_PAGE_LOGIN).forward(req,resp);
        }

    }
}
